
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.document.operation.impl.impl {
import org.waveprotocol.wave.model.document.operation.BufferedDocInitialization;
import org.waveprotocol.wave.model.document.operation.DocInitializationCursor;
import org.waveprotocol.wave.model.document.operation.DocumentOperation;
import org.waveprotocol.wave.model.document.operation.DocOpComponentType;  import org.waveprotocol.wave.model.document.operation.util.DocOpComponentConstants;
import org.waveprotocol.wave.model.document.operation.DocumentOperationCursor;
import org.waveprotocol.wave.model.document.operation.impl.AbstractDocInitialization;
import org.waveprotocol.wave.model.util.StringBuilder;

public final class XMLDocInitializtion extends AbstractDocInitialization {
	
	
	var index:int= 0;
	var docItem:int= 0;
	var target:DocInitializationCursor;
	
	var indicesB:StringBuilder;
	var exploded:BufferedDocInitialization;
	var numDocComponents:int;
	var builders:Array;
	var opStringifier:DocumentOperationCursor; 
	var op:DocumentOperation;
	
	private var docCompType:DocOpComponentType;
	
	public function XMLDocInitializtion(indicesB:StringBuilder,
										exploded:BufferedDocInitialization, numDocComponents:int,
										builders:Array, opStringifier:DocumentOperationCursor, op:DocumentOperation) {
		this.indicesB = indicesB;
		this.exploded = exploded;
		this.numDocComponents = numDocComponents;
		this.builders = builders;
		this.opStringifier = opStringifier;
		this.op = op;
		
	}
	
	function runTarget(itemCount:int):void {
		indicesB.append(docItem);
		docItem += itemCount;
		while (index < numDocComponents && itemCount > 0) {
			exploded.applyComponentDocInit(index, target);
			if (exploded.getType(index) != DocOpComponentConstants.ANNOTATION_BOUNDARY) {
				itemCount--;
			}
			index++;
		}
	}
	
	function matchUp():void {
		var max:int= 0;
		for (var i:int = 0; i< builders.length; i++) {
			var b:StringBuilder = StringBuilder(builders[i]);
			max = Math.max(max, b.length());
		}
		for (var i:int = 0; i< builders.length; i++) {
			var b:StringBuilder = StringBuilder(builders[i]);
			while (b.length() < max) {
				b.append(' ');
			}
		}
	}
	
	
	override public function applyDocInit(c:DocInitializationCursor):void {
		target = c;
		op.apply(new VisualizeDocOpCursor(this));
		runTarget(1);
	}
	
}
}